package org.forum.dao.base;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;

public class BaseDaoImpl<T> implements BaseDao<T>{
	
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public T get(Class<T> entityClazz, Serializable id) {
		return (T)getSessionFactory().getCurrentSession().get(entityClazz, id);
	}

	@Override
	public Serializable save(T entity) {
		return getSessionFactory().getCurrentSession().save(entity);
	}

	@Override
	public void update(T entity) {
		getSessionFactory().getCurrentSession().saveOrUpdate(entity);
	}

	@Override
	public void delete(T entity) {
		getSessionFactory().getCurrentSession().delete(entity);
	}

	@Override
	public void delete(Class<T> entityClazz, Serializable id) {
		//数据库表不区分大小写
		getSessionFactory().getCurrentSession().createQuery("delete " + entityClazz.getSimpleName() + " en where en.id="
				+ "?0").setParameter("0", id).executeUpdate();
	}

	@Override
	public List<T> findAll(Class<T> entityClazz) {
		return find("SELECT en FROM " + entityClazz.getSimpleName() + " en");
	}

	@Override
	public long findCount(Class<T> entityClazz) {
		List<?> l = find("SELECT COUNT(*) FROM " + entityClazz.getSimpleName());
		if(l != null && l.size() == 1){
			return (Long)l.get(0);
		}
		return 0;
	}

	/*
	 * 执行sql语句
	 */
	@SuppressWarnings("unchecked")
	protected List<T> find(String hql){
		return (List<T>)getSessionFactory().getCurrentSession().createQuery(hql).list();
	}

}
